#!/bin/bash
#
#   This is a wrapper for qsub (of torque). It waits until the submitted
# commands (from stdin) are finished on computational nodes, and provides
# the return value from the last command. Also, it captures KILL signals
# to stop the remote running tasks.

RET=0
STDOUT=$(mktemp)
STDERR=$(mktemp)
JOB_ID=$( (cat; echo ';echo $?') | qsub -d "$(pwd)" -o "${STDOUT}" -e "${STDERR}" $*)

function kill_job
{
	qdel ${JOB_ID}
	RET=1
	exit ${RET}
}
trap kill_job INT
trap kill_job ABRT
trap kill_job QUIT
trap kill_job TERM

while qstat ${JOB_ID} >/dev/null 2>/dev/null; do
	sleep 5;
done

RET=$(cat ${STDOUT})
rm -f ${STDOUT} ${STDERR}

exit ${RET}
